package com.xinyues.gamemanager.security;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.alibaba.fastjson.JSONObject;
import com.xinyues.gamemanager.common.InputStreamUtil;

public class AjaxJsonUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    private Logger logger = LoggerFactory.getLogger(AjaxJsonUsernamePasswordAuthenticationFilter.class);

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")) { // 必须以post方式提交
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        String username = "";
        String password = "";
        try {
            if(request.getInputStream().markSupported()) {
                request.getInputStream().mark(Integer.MAX_VALUE);
            }
            String json = InputStreamUtil.readInputStream(request.getInputStream());
            if(request.getInputStream().markSupported()) {
                request.getInputStream().reset();
            }
            JSONObject param = JSONObject.parseObject(json);
            username = param.getString("username");
            password = param.getString("password");
        } catch (IOException e) {
            logger.error("读取登陆数据失败", e);
        }
        username = username.trim();
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
        return this.getAuthenticationManager().authenticate(authRequest);
    }
}
